<?php

/* 子管理会员控制器 */
class User_subApp extends BackendApp
{
	var $_admin_mod;
	var $_user_mod;

	function __construct()
	{
		$this->UserApp();
	}

	function UserApp()
	{
		parent::__construct();
		$this->_user_mod =& m('member');
		$this->_admin_mod = & m('userpriv');
	}

	function index()
	{
		//当前用户类型
		$type  = $this->visitor->get('type');
		$user_id  = $this->visitor->get('user_id');
		$this->assign('type',$type);
		$conditions = $this->_get_query_conditions(array(
			array(
				'field' => $_GET['field_name'],
				'name'  => 'field_value',
				'equal' => 'like',
			),
		));
		if(!empty($type)){
			$where = ' and prevuid='.$user_id;
		}else{
			echo "您无权操作";exit;
		}
		//更新排序
		if (isset($_GET['sort']) && !empty($_GET['order']))
		{
			$sort  = strtolower(trim($_GET['sort']));
			$order = strtolower(trim($_GET['order']));
			if (!in_array($order,array('asc','desc')))
			{
				$sort  = 'user_id';
				$order = 'asc';
			}
		}
		else
		{
			if (isset($_GET['sort']) && empty($_GET['order']))
			{
				$sort  = strtolower(trim($_GET['sort']));
				$order = "";
			}
			else
			{
				$sort  = 'user_id';
				$order = 'asc';
			}
		}
		$page = $this->_get_page();
		
		$db=&db();
		$sql="SELECT member.*,d1.d_value,p1.o_name, s.store_id,user_priv.store_id as 
priv_store_id,user_priv.privs, member.user_id FROM zys_member member 
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 ".$conditions.$where." ORDER BY member.user_id asc LIMIT ".$page['limit'];
		$users=$db->getAll($sql);
		$sql2="select count(*)  FROM zys_member member
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 ".$conditions.$where;
		$users_count=$db->getone($sql2);

		foreach ($users as $key => $val)
		{
			if ($val['priv_store_id'] == 0 && $val['privs'] != '')
			{
				$users[$key]['if_admin'] = true;
			}
		}
		$this->assign('users', $users);
		$page['item_count'] = $users_count;
		$this->_format_page($page);
		$this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
		$this->assign('page_info', $page);
		/* 导入jQuery的表单验证插件 */
		$this->import_resource(array(
            'script' => 'jqtreetable.js,inline_edit.js',
            'style'  => 'res:style/jqtreetable.css'
            ));
            $this->assign('query_fields', array(
            'user_name' => LANG::get('user_name'),
            'email'     => LANG::get('email'),
            'real_name' => LANG::get('real_name'),
            //            'phone_tel' => LANG::get('phone_tel'),
            //            'phone_mob' => LANG::get('phone_mob'),
            ));
            $this->assign('sort_options', array(
            'reg_time DESC'   => LANG::get('reg_time'),
            'last_login DESC' => LANG::get('last_login'),
            'logins DESC'     => LANG::get('logins'),
            ));
            $this->display('user_sub.index.html');
	}

	function add()
	{
		//当前用户类型
		$type  = $this->visitor->get('type');
		$this->assign('type',$type);
		if (!IS_POST)
		{
			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
			$this->display('user_sub.form.html');
		}
		else
		{
			$user_name = trim($_POST['user_name']);
			$password  = trim($_POST['password']);
			$email     = trim($_POST['email']);
			$phone_tel = trim($_POST['phone_tel']);

			if (strlen($user_name) < 3 || strlen($user_name) > 25)
			{
				$this->show_warning('user_name_length_error');

				return;
			}

			if (strlen($password) < 6 || strlen($password) > 20)
			{
				$this->show_warning('password_length_error');

				return;
			}

			if (!is_email($email))
			{
				$this->show_warning('email_error');

				return;
			}
			if(!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", $phone_tel)){

				$this->show_warning('手机错误');
				return;
			}
			/* 连接用户系统 */
			$ms =& ms();

			/* 检查名称是否已存在 */
			if (!$ms->user->check_username($user_name))
			{
				$this->show_warning($ms->user->get_error());
				return;
			}
			/* 保存本地资料 */
			$data = array(
                'real_name' => trim($_POST['real_name']),
                'gender'    => intval($_POST['gender']),
			    'phone_tel' => $_POST['phone_tel'],
				'unit' => $this->visitor->get('unit'),
				'type' => intval($type),
				'prevuid'=> $this->visitor->get('user_id'),
				'giveauth' => isset($_POST['giveauth'])?intval($_POST['giveauth']):0
			);
			/* 到用户系统中注册 */
			$user_id = $ms->user->register($user_name, $password, $email, $data);
			if (!$user_id)
			{
				$this->show_warning($ms->user->get_error());

				return;
			}
			$this->show_message('添加成功','返回会员', 'index.php?app=user_sub&act=edit&id='.$user_id);
		}
	}

	/*检查会员名称的唯一性*/
	function  check_user()
	{
		$user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
		if (!$user_name)
		{
			echo ecm_json_encode(false);
			return ;
		}

		/* 连接到用户系统 */
		$ms =& ms();
		echo ecm_json_encode($ms->user->check_username($user_name));
	}
	function edit()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST)
		{
			/* 是否存在 */
			$sql = "select m.*,op.o_name from zys_member as m left join zys_operator as op on m.unit =op.o_tid where m.user_id=".$id;
			$db = &db();
			$user = $db->getRow($sql);
			if (!$user)
			{
				$this->show_warning('user_empty');
				return;
			}
			$type  = $this->visitor->get('type');
			$this->assign('type',$type);
			$this->assign('user', $user);
			$this->assign('phone_tel', explode('-', $user['phone_tel']));
			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
            $this->display('user_sub.form.html');
		}
		else
		{
			$data = array(
				'real_name' => trim($_POST['real_name']),
				'gender'    => intval($_POST['gender']),
				'phone_tel' => $_POST['phone_tel'],
				'unit' => $this->visitor->get('unit'),
				'type' => intval($_POST['type']),
				'prevuid'=> $this->visitor->get('user_id'),
				'giveauth' => isset($_POST['giveauth'])?intval($_POST['giveauth']):0
			);
			if (!empty($_POST['password']))
			{
				$password = trim($_POST['password']);
				if (strlen($password) < 6 || strlen($password) > 20)
				{
					$this->show_warning('password_length_error');

					return;
				}
			}
			if (!is_email(trim($_POST['email'])))
			{
				$this->show_warning('email_error');

				return;
			}
			if(!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", trim($_POST['phone_tel']))){

				$this->show_warning('手机错误');
				return;
			}
			/* 修改本地数据 */
			$this->_user_mod->edit($id, $data);

			/* 修改用户系统数据 */
			$user_data = array();
			!empty($_POST['password']) && $user_data['password'] = trim($_POST['password']);
			!empty($_POST['email'])    && $user_data['email']    = trim($_POST['email']);
			if (!empty($user_data))
			{
				$ms =& ms();
				$ms->user->edit($id, '', $user_data, true);
			}
			$this->show_message('编辑成功','edit_again',   'index.php?app=user_sub&act=edit&id=' . $id	);
		}
	}
	function ajax_col()
	{
		$id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$column = empty($_GET['column']) ? '' : trim($_GET['column']);
		$value  = isset($_GET['value']) ? trim($_GET['value']) : '';
		$data   = array();
		if (in_array($column ,array('del')))
		{
			$data[$column] = $value;
			$this->_user_mod->edit($id, $data);
			if(!$this->_user_mod->has_error())
			{
				echo ecm_json_encode(true);
			}
		}
		else
		{
			return ;
		}
		return ;
	}

	function drop()
	{
		$db=&db();
		$id = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$id)
		{
			$this->show_warning('no_user_to_drop');
			return;
		}
		$admin_mod =& m('userpriv');
		if(!$admin_mod->check_admin($id))
		{
			$this->show_message('cannot_drop_admin','drop_admin', 'index.php?app=admin');
			return;
		}
		$ids = explode(',', $id);

		/* 连接用户系统，从用户系统中删除会员 */
		$ms =& ms();
		if (!$ms->user->drop($ids))
		{
			foreach ($ids as $k=>$v){
				$sql="select username from cw_member where user_id=".$v;
				$username=$db->getOne();
					
				if($username){
					$url = "http://192.168.0.189:9090/plugins/userService/userservice?type=delete&secret=0wBfHo6f&username=".$username;
					$f = fopen($url,'r');
					$response = fread($f, 1024);
					fclose($f);
				}
			}
			$this->show_warning($ms->user->get_error());

			return;
		}

		$this->show_message('删除成功');
	}

	//展示并添加权限
	function power(){
		$id = (isset($_GET['id']) && $_GET['id'] !='') ? intval($_GET['id']) : 0;
		if (!IS_POST)
		{
			//获取当前管理员权限
			$privs = $this->_admin_mod->get(array(
				'conditions' => '1=1 AND  store_id =0 AND user_id = '.$id,
				'fields' => 'privs',
			));
			$users = $this->_user_mod->get(array(
				'conditions' => '1=1 AND user_id ='.$id,
				'fields' => 'user_name,real_name,prevuid',
			));
			//获取上级的权限
			$prevpower = $this->_admin_mod->get(array(
				'conditions' => '1=1 AND  store_id =0 AND user_id = '.$users['prevuid'],
				'fields' => 'privs',
			));
			include(ROOT_PATH.'/admin/includes/priv.inc.php');
			if($prevpower['privs']!='all'){
				$priv=explode(',', $prevpower['privs']);
				foreach ($menu_data as $k=>$v){
					foreach($v as $k1=>$v1){
						if(!in_array($v1, $priv)){
							unset($menu_data[$k][$k1]);
						}
					}

				}
				foreach ($menu_data as $k=>$v){
					if(!$v){
						unset($menu_data[$k]);
					}
				}
			}
			$priv=explode(',', $privs['privs']);
			$act = 'edit';
			$this->assign('act',$act);
			$this->assign('user',$users);
			$this->assign('checked_priv',$priv);
			$this->assign('priv',$menu_data);
			$this->display('user_power.form.html');
		}else
		{
			//更新管理员权限
			$privs = (isset($_POST['priv']) && $_POST['priv']!='priv') ? $_POST['priv']: '';
			$priv = '';
			if ($privs == '')
			{
				$this->show_warning('选择要添加的权限','','index.php?app=user_sub&act=power&id='.$id);
				return;
			}
			else
			{
				$priv = implode(',', $privs);
			}
			$data = array(
				'user_id' => $id,
				'store_id' => '0',
				'privs' => $priv,
			);
			$privs = $this->_admin_mod->get(array(
				'conditions' => '1=1 AND  store_id =0 AND user_id = '.$id,
				'fields' => 'privs',
			));
			if(!empty($privs)){
				$this->_admin_mod->edit($id, $data);
			}else{
				$this->_admin_mod->add($data);
			}
			if($this->_admin_mod->has_error())
			{
				$this->show_warning($this->_admin_mod->get_error(),'','index.php?app=user_sub&act=power&id='.$id);
				return;
			}
			$this->show_message('设置成功','','index.php?app=user_sub&act=power&id='.$id);
			return true;
		}
	}
	/**
	 * 上传头像
	 *
	 * @param int $user_id
	 * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
	 */
	function _upload_portrait($user_id)
	{
		$file = $_FILES['portrait'];
		if ($file['error'] != UPLOAD_ERR_OK)
		{
			return '';
		}

		import('uploader.lib');
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE);
		$uploader->addFile($file);
		if ($uploader->file_info() === false)
		{
			$this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=user&amp;act=edit&amp;id=' . $user_id);
			return false;
		}
		$imgname=gmtime();
		$uploader->root_dir(ROOT_PATH);
		return $uploader->save('data/files/mall/portrait/' . ceil($user_id / 500), $imgname);
	}
}

?>
